﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Clmp.Data.DBEntity2.Sql
{
    public class SqlEntityServer : IDbEntityServer
    {
        public SqlEntityServer(IMapping mapping)
        {
            this.Mapping = mapping;
        }
        IMapping Mapping { get; set; }
        #region IDbEntityServer 成员

        public string GetInsertSqlString<T>(T entity) where T : Entity
        {
            string pkName = Mapping.GetTableName<T>();
            StringBuilder sql = new StringBuilder("INSERT INTO [").Append(pkName).Append("]");
            StringBuilder props = new StringBuilder(" (");
            StringBuilder propVals = new StringBuilder(" (");

            var propDic = entity.GetPropertyDictionary();
            if (propDic == null || propDic.Count == 0)
                throw new ArgumentException("待插入的实体不包含任何已赋值的属性，至少为实体的一个属性赋值。");      //TODO:异常类型修改

            foreach (var prop in propDic)
            {
                props.Append(",[").Append(prop.Key).Append("]");
                propVals.Append(",@").Append(prop.Key);
            }
            props.Remove(2, 1).Append(") ");
            propVals.Remove(2, 1).Append(") ");

            sql.Append(props.ToString())
                .Append(" VALUES")
                .Append(propVals.ToString());

            return sql.ToString();
        }

        public string GetUpdateSqlString<T>(T entity) where T : Entity
        {
            StringBuilder sql = new StringBuilder("UPDATE [").Append(Mapping.GetTableName<T>()).Append("] SET ");
            StringBuilder props = new StringBuilder();
            string primaryKey = Mapping.GetTablePrimaryKey<T>();

            foreach (var prop in entity.GetPropertyDictionary())
            {
                if (prop.Key != primaryKey)
                {
                    props.Append(",[").Append(prop.Key).Append("]=@").Append(prop.Key);
                }
            }

            props.Remove(0, 1);

            sql.Append(props.ToString())
                .Append(" WHERE [" + primaryKey + "]=@ID");

            return sql.ToString();
        }

        public string GetDeleteSqlString<T>(int id) where T : Entity
        {
            string sql = "DELETE FROM [" + Mapping.GetTableName<T>() + "] WHERE [" + Mapping.GetTablePrimaryKey<T>() + "]=@ID";
            return sql;
        }

        public string GetGetOneSqlString<T>(int id) where T : Entity
        {
            string sql = "SELECT TOP 1 * FROM [" + Mapping.GetTableName<T>() + "] WHERE [" + Mapping.GetTablePrimaryKey<T>() + "]=@ID";
            return sql;
        }

        public string GetPrimaryKeyName<T>() where T : Entity
        {
            return Mapping.GetTablePrimaryKey<T>();
        }

        #endregion
    }
}
